<template>
  <Form
    ref="formRef"
    :model="mainForm"
    :rules="rules"
    :labelCol="{ span: 2 }"
    :wrapperCol="{ span: 22 }"
  >
    <FormItem label="别名" name="slug">
      <Input
        v-model:value="mainForm.slug"
        :addonBefore="BLOG_SITE"
        placeholder="article-title"
      ></Input>
    </FormItem>
    <FormItem label="标题" name="title">
      <Input v-model:value="mainForm.title" placeholder="文章标题"></Input>
    </FormItem>
    <FormItem label="描述" name="description">
      <Textarea v-model:value="mainForm.description" :rows="4" placeholder="文章描述"></Textarea>
    </FormItem>
    <FormItem label="关键词" name="keywords">
      <Select v-model:value="mainForm.keywords" mode="tags" placeholder="输入关键词后回车"></Select>
    </FormItem>
    <FormItem label="标签" name="tag">
      <Spin :spinning="loading.state.value">
        <Space :wrap="true" :size="[12, 12]">
          <template v-if="!tags.length">
            <TypographyText type="secondary">无数据</TypographyText>
          </template>
          <template v-else>
            <Button
              size="small"
              v-for="tag in tags"
              :key="tag._id!"
              :type="mainForm.tag.includes(tag._id!) ? 'primary' : 'default'"
              @click="handleClick(tag)"
            >
              <template #icon>
                <template v-if="mainForm.tag.includes(tag._id!)">
                  <CheckCircleOutlined />
                </template>
                <template v-else>
                  <TagOutlined />
                </template>
              </template>
              {{ tag.name }}
            </Button>
          </template>
          <Divider type="vertical" />
          <Button size="small" type="dashed" :loading="loading.state.value" @click="fetchTags">
            <template #icon>
              <ReloadOutlined />
            </template>
            刷新列表
          </Button>
        </Space>
      </Spin>
    </FormItem>
    <FormItem label="内容" name="content" :required="true">
      <UniversalEditor
        v-model:value="mainForm.content"
        :formStatus="true"
        :minRows="28"
        placeholder="输入文章内容..."
      />
    </FormItem>
  </Form>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, PropType, toRaw, watchEffect } from 'vue'
import {
  Button,
  Divider,
  Form,
  FormInstance,
  FormItem,
  Input,
  Select,
  Space,
  Spin,
  Textarea,
  TypographyText,
} from 'ant-design-vue'
import type { Article } from '@/constants/article'
import { Tag } from '@/constants/tag'
import { useLoading } from '@/handcer'
import { getTags } from '@/store/tag'
import { BLOG_SITE } from '@/config'
import UniversalEditor from '@/components/UniversalEditor/index.vue'
import { CheckCircleOutlined, TagOutlined, ReloadOutlined } from '@ant-design/icons-vue'

export type BaseFormModel = Partial<
  Pick<Article, 'slug' | 'tag' | 'title' | 'content' | 'keywords' | 'description'>
>

export interface MainForm {
  slug: string
  title: string
  content: string
  description: string
  tag: Array<string>
  keywords: Array<string>
}

export interface MainFormExpose {
  validate: () => Promise<MainForm>
}

const props = defineProps({
  form: {
    type: Object as PropType<BaseFormModel>,
  },
})

const mainForm = reactive<MainForm>({
  title: '',
  content: '',
  description: '',
  slug: '',
  tag: [],
  keywords: [],
})

const rules = {
  slug: [{ required: true, message: '请输入别名' }],
  title: [{ required: true, message: '请输入标题' }],
  description: [{ required: true, message: '请输入描述' }],
  keywords: [{ required: true, message: '请输入关键词' }],
  content: [{ required: true, message: '请输入文章内容' }],
}

// 获取标签
const formRef = ref<FormInstance>()
const loading = useLoading()
const tags = ref<Array<Tag>>([])
const fetchTags = () => {
  loading.promise(getTags({ per_page: 50 })).then((result) => (tags.value = result.data))
}
const handleClick = (tag: Tag) => {
  const tagID = tag._id!
  const isChecked = mainForm.tag?.includes(tagID)
  const tagIDs = !isChecked ? [...mainForm.tag, tagID] : mainForm.tag?.filter((t) => t !== tagID)
  mainForm.tag = tagIDs
}

const validate = () => {
  return new Promise((resolve, reject) => {
    formRef.value
      ?.validateFields()
      .then(() => {
        const data = toRaw(mainForm)
        resolve(data)
      })
      .catch((err) => {
        const nameList = Object.keys(err.values)
        formRef.value?.scrollToField(nameList[0], {
          behavior: 'smooth',
        })
        reject(err)
      })
  })
}

watchEffect(() => {
  mainForm.title = props.form?.title!
  mainForm.content = props.form?.content!
  mainForm.description = props.form?.description!
  mainForm.slug = props.form?.slug!
  mainForm.tag = props.form?.tag!
  mainForm.keywords = props.form?.keywords!
})

onMounted(() => {
  fetchTags()
})

// 暴露方法
defineExpose({
  validate,
})
</script>

<style lang="less" scoped></style>
